package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author wzh
 * @since 2022-09-21
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(EduSubjectService eduSubjectService, MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        QueryWrapper<EduSubject> oneQueryWrapper=new QueryWrapper<>();
        oneQueryWrapper.eq("parent_id",0);
        List<EduSubject> oneEduSubjects = baseMapper.selectList(oneQueryWrapper);

        QueryWrapper<EduSubject> twoQueryWrapper=new QueryWrapper<>();
        oneQueryWrapper.ne("parent_id",0);
        List<EduSubject> twoEduSubjects = baseMapper.selectList(twoQueryWrapper);

        List<OneSubject> res=new LinkedList<>();
        for (EduSubject oneEduSubject : oneEduSubjects) {
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(oneEduSubject,oneSubject);

            List<TwoSubject> twoSubjects=new ArrayList<>();
            //遍历二级
            for (EduSubject twoEduSubject : twoEduSubjects) {
                //判断二级分类是哪个一级分类的
                if (twoEduSubject.getParentId().equals(oneEduSubject.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(twoEduSubject,twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);
            res.add(oneSubject);
        }

        return res;
    }
}
